package cn.neusoft.yp.shiro;


import cn.neusoft.yp.pojo.User;
import cn.neusoft.yp.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;


public class AuthRealm extends AuthorizingRealm{
	@Autowired
	private UserService userService;

	//权限控制
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

		/**
		 * 权限控制的实现
		 * 1.获取用户信息
		 */
		User user=(User) SecurityUtils.getSubject().getPrincipal();
		String role=user.getRole();

		SimpleAuthorizationInfo info =new SimpleAuthorizationInfo();
		info.addStringPermission(role);
		return info;

	}

	@Override
	//登陆认证模块
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		//为shiro安全管理器提供真实的用户信息

		//1.根据用户输入的用户名userName查询正确的用户信息
		UsernamePasswordToken loginToken=(UsernamePasswordToken) token;
		String username = loginToken.getUsername();

		User user=userService.findUserByUsername(username);
		//2.将user真实信息返回给shiro安全管理器
		AuthenticationInfo info=new SimpleAuthenticationInfo(user, user.getPassword(),this.getName());
		return info;
	}
}
